/*
 * @Author: tanjunyi@doctorwork.com
 * @Date: 2020-06-17 09:14:57
 * @LastEditors: tanjunyi@doctorwork.com
 * @LastEditTime: 2020-06-21 19:10:59
 * @Description:
 */
//  把 data中的数据都是用Object.defineProperty重新定义
import { isObject, def } from '../util/index'
import { arraryMethods } from './arrary'
import Dep from './dep';
class Observer {
	constructor(data) {
		def(data, '__ob__', this);
		// Object.defineProperty 无法深层次监听数据
		if (Array.isArray(data)) {
			// 去操作数组的push shift unshift
			data.__proto__ = arraryMethods;
			// 循环监控数组的每一项
			this.observerArrary(data);
		} else {
			this.walk(data);
		}
	}
	observerArrary(value) {
		for (var i = 0; i < value.length; i++) {
			observe(value[i])
		}
	}
	walk(data) {
		let keys = Object.keys(data);
		keys.forEach((key, index) => {
			defineReactive(data, key, data[key])

		})
	}
}

function defineReactive(data, key, value) {
	observe(value);
	let dep = new Dep();
	Object.defineProperty(data, key, {
		get() {
			if (Dep.target) {
				dep.depend(); //让dep去收集watcher
			}
			console.log("get dep:", dep)
			return value;
		},
		set(newValue) {
			if (newValue === value) return;
			observe(newValue); //继续劫持用户设置的新数据， 用户设置的可能是一个新对象
			value = newValue;
			dep.notify();
		}
	})
}

export function observe(data) {
	let isobject = isObject(data);
	if (!isobject) return;
	return new Observer(data); //用来观测数据
}